<template>
  <a-card :style="{ width: '500px' }">
    <a-button @click="onClick" :style="{ marginBottom: '16px' }" :loading="loading">
      {{ loading ? 'Running' : 'Run Next' }}
    </a-button>
    <ThoughtChain :items="items" />
  </a-card>
</template>

<script setup name="BubbleThoughtChain">
import { ref } from 'vue'
import { CheckCircleOutlined, InfoCircleOutlined, LoadingOutlined } from '@ant-design/icons-vue'
import { ThoughtChain } from 'ant-design-x-vue'

const getStatusIcon = (status) => {
  switch (status) {
    case 'success':
      return h(CheckCircleOutlined)
    case 'error':
      return h(InfoCircleOutlined)
    case 'pending':
      return h(LoadingOutlined)
    default:
      return undefined
  }
}

const mockServerResponseData = [
  {
    title: 'Thought Chain Item - 1',
    status: 'success',
    description: 'status: success',
    icon: getStatusIcon('success')
  },
  {
    title: 'Thought Chain Item - 2',
    status: 'error',
    description: 'status: error',
    icon: getStatusIcon('error')
  }
]

const delay = (ms) => {
  return new Promise((resolve) => {
    const timer = setTimeout(() => {
      clearTimeout(timer)
      resolve()
    }, ms)
  })
}

const addChainItem = () => {
  mockServerResponseData.push({
    title: `Thought Chain Item - ${mockServerResponseData.length + 1}`,
    status: 'pending',
    icon: getStatusIcon('pending'),
    description: 'status: pending'
  })
}

const updateChainItem = async (status) => {
  await delay(800)
  mockServerResponseData[mockServerResponseData.length - 1].status = status
  mockServerResponseData[mockServerResponseData.length - 1].icon = getStatusIcon(status)
  mockServerResponseData[mockServerResponseData.length - 1].description = `status: ${status}`
}

const items = ref(mockServerResponseData)
const loading = ref(false)

const mockStatusChange = async () => {
  await updateChainItem('error')
  items.value = [...mockServerResponseData]
  await updateChainItem('pending')
  items.value = [...mockServerResponseData]
  await updateChainItem('success')
  items.value = [...mockServerResponseData]
}

const onClick = async () => {
  loading.value = true
  addChainItem()
  items.value = [...mockServerResponseData]
  await mockStatusChange()
  loading.value = false
}
</script>